package com.lemon.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HttpUtil
{

	private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
	
	private static final int    conntimeout = 30 * 1000;
	private static final int    readtimeout = 30 * 1000;
	private static final String charset     = "UTF-8";//"UTF-8"  GBK

	//url

	public static final String TKLM_SEARCH = "https://pub.alimama.com/items/search.json";
	
	/**
	 * @Title: doPost
	 * @Description:
	 * @param @param url
	 * @param @param data
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 * 		@date 2014-1-2 下午1:06:58
	 */
	public static String doPost(String url, String data) {
		//读取返回内容
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection con = null;
		//尝试发送请求
		try
		{
			con = (HttpURLConnection) new URL(url).openConnection();
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setConnectTimeout(conntimeout);
			con.setReadTimeout(readtimeout);
//			con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			con.setRequestProperty("content-type" , "application/json;charset=utf-8");
			con.setRequestProperty("contentType", "utf-8");  
			OutputStream out = con.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(out, charset);
			String wr = new String(data.getBytes(), charset);
			osw.write(wr);
			osw.flush();
			osw.close();
			out.flush();
			out.close();
			//System.out.println("code:"+con.getResponseCode());
			if (con.getResponseCode() == 200)
			{
				InputStream in = con.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(in, charset));
				String temp;
				while ((temp = br.readLine()) != null)
				{
					buffer.append(temp);
					//buffer.append("\n");
				}
				in.close();
				br.close();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (con != null)
			{
				con.disconnect();
				con = null;
			}
		}
		return buffer.toString();
	}
	
	/**
	 * @Title: doGet
	 * @Description:
	 * @param @param url
	 * @param @param params
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 * 		@date 2014-1-2 下午1:09:42
	 */
	public static String doGet(String url, Map<String, String> params) {
		//读取返回内容
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection con = null;
		//尝试发送请求
		try
		{
			//构建请求参数
			StringBuffer sb = new StringBuffer();
			if (params != null)
			{
				for (Entry<String, String> e : params.entrySet())
				{
					sb.append(e.getKey());
					sb.append("=");
					sb.append(URLEncoder.encode(e.getValue(),charset));
					sb.append("&");
				}
				sb.substring(0, sb.length() - 1);
			}
			con = (HttpURLConnection) new URL(url+"?"+sb.toString()).openConnection();
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setConnectTimeout(conntimeout);
			con.setReadTimeout(readtimeout);
			con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			if (con.getResponseCode() == 200)
			{
				InputStream in = con.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(in, charset));
				String temp;
				while ((temp = br.readLine()) != null)
				{
					buffer.append(temp);
					//buffer.append("\n");
				}
				in.close();
				br.close();
			}
		}
		catch (Exception e)
		{
			//e.printStackTrace();
		}
		finally
		{
			if (con != null)
			{
				con.disconnect();
				con = null;
			}
		}
		return buffer.toString();
	}
	
	/**
	 * @Title: doHttp
	 * @Description:
	 * @param @param url
	 * @param @param params
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 * 		@date 2013-12-13 上午10:35:32
	 */
	public static String doPost(String url, Map<String, String> params) {
		//读取返回内容
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection con = null;
		//构建请求参数
		StringBuffer sb = new StringBuffer();
		if (params != null)
		{
			for (Entry<String, String> e : params.entrySet())
			{
				sb.append(e.getKey());
				sb.append("=");
				sb.append(e.getValue());
				sb.append("&");
			}
			sb.substring(0, sb.length() - 1);
		}
		//尝试发送请求
		try
		{
			con = (HttpURLConnection) new URL(url).openConnection();
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setConnectTimeout(conntimeout);
			con.setReadTimeout(readtimeout);
			con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			OutputStream out = con.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(out, charset);
			osw.write(sb.toString());
			osw.flush();
			osw.close();
			out.flush();
			out.close();
			if (con.getResponseCode() == 200)
			{
				InputStream in = con.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(in, charset));
				String temp;
				while ((temp = br.readLine()) != null)
				{
					buffer.append(temp);
					//buffer.append("\n");
				}
				in.close();
				br.close();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (con != null)
			{
				con.disconnect();
				con = null;
			}
		}
		return buffer.toString();
	}
	
	/**
	 * @Title: doPost
	 * @Description:
	 * @param @param url
	 * @param @param list
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 * 		@date 2013-12-13 上午10:35:39
	 */
	public static String doPost(String url, ArrayList<Entry<String, String>> list) {
		//读取返回内容
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection con = null;
		//构建请求参数
		StringBuffer sb = new StringBuffer();
		if (list != null)
		{
			for (Entry<String, String> e : list)
			{
				sb.append(e.getKey());
				sb.append("=");
				sb.append(e.getValue());
				sb.append("&");
			}
			sb.substring(0, sb.length() - 1);
		}
		//尝试发送请求
		try
		{
			con = (HttpURLConnection) new URL(url).openConnection();
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setConnectTimeout(conntimeout);
			con.setReadTimeout(readtimeout);
			con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			OutputStream out = con.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(out, charset);
			osw.write(sb.toString());
			osw.flush();
			osw.close();
			out.flush();
			out.close();
			if (con.getResponseCode() == 200)
			{
				InputStream in = con.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(in, charset));
				String temp;
				while ((temp = br.readLine()) != null)
				{
					buffer.append(temp);
					//buffer.append("\n");
				}
				in.close();
				br.close();
			}
		}
		catch (Exception e)
		{
			//e.printStackTrace();
		}
		finally
		{
			if (con != null)
			{
				con.disconnect();
				con = null;
			}
		}
		return buffer.toString();
	}
	
	/**
	 * @Title: doHttp
	 * @Description:
	 * @param @param url
	 * @param @param params
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 * 		@date 2013-12-13 上午10:35:32
	 */
	public static String doPost1(String url, Map<String, String> params) {
		//读取返回内容
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection con = null;
		//构建请求参数
		StringBuffer sb = new StringBuffer();
		if (params != null)
		{
			for (Entry<String, String> e : params.entrySet())
			{
				sb.append(e.getKey());
				sb.append("=");
				sb.append(e.getValue());
				sb.append("&");
			}
			sb.substring(0, sb.length() - 1);
		}
		//尝试发送请求
		try
		{
			url = url+"?"+sb;
			System.out.println(url);
			con = (HttpURLConnection) new URL(url).openConnection();
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setConnectTimeout(conntimeout);
			con.setReadTimeout(readtimeout);
			con.setRequestProperty("Content-Type" , "application/x-www-form-urlencoded");
			OutputStream out = con.getOutputStream();
			OutputStreamWriter osw = new OutputStreamWriter(out, charset);
			osw.write(sb.toString());
			osw.flush();
			osw.close();
			out.flush();
			out.close();
			if (con.getResponseCode() == 200)
			{
				InputStream in = con.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(in, charset));
				String temp;
				while ((temp = br.readLine()) != null)
				{
					buffer.append(temp);
					//buffer.append("\n");
				}
				in.close();
				br.close();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (con != null)
			{
				con.disconnect();
				con = null;
			}
		}
		return buffer.toString();
	}
	
	/**
	 * @Title: getUsrIPAddr
	 * @Description:(一句话阐述): 获取用户的ip地址
	 * @param request
	 * @return    
	 * @author Ran_cc
	 * @date 2018年3月21日
	 */
	 public static String getUsrIPAddr(HttpServletRequest request) {  
	        String ip = "";  
	        ip = request.getHeader("x-forwarded-for");  
	       //2.如果squid.conf的配制文件forwarded_for项默认是off，则：X-Forwarded-For：unknown。考虑用Proxy-Client-IP或WL-Proxy-Client-IP获取  
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getHeader("Proxy-Client-IP");  
	        }  
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getHeader("WL-Proxy-Client-IP");  
	        }  
	        //3.最后考虑没有代理的情况，直接用request.getRemoteAddr()获取ip  
	        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	            ip = request.getRemoteAddr();  
	        }  
	        //4.如果通过多级反向代理，则可能产生多个ip，其中第一个非unknown的IP为客户端真实IP（IP按照','分割）  
	        if(ip != null && ip.split(",").length > 1){  
	            ip = (ip.split(","))[0];  
	       }          
	       //5.如果是服务器本地访问，需要根据网卡获取本机真实ip  
	       if("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {  
	            try {  
	                ip = InetAddress.getLocalHost().getHostAddress();  
	           } catch (UnknownHostException e) {  
	                return "";  
	            }  
	       }
	       return ip; 
	    }
	
}
